package com.vancouver.knows.ui.activity;

import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.Selection;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLayoutChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;

import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.StringUtil;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.Constants;
import com.vancouver.knows.business.bean.CommentInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.UserInsertCommentTaskMark;
import com.vancouver.knows.ui.activity.citynews.CityNewsCommentsActivity;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.util.PhoConstants;

/**
 * 城惠详情
 * 
 * @author cxlin
 * 
 */
abstract public class CommentDetailActivity<T> extends BaseActivity implements IResultReceiver, OnLayoutChangeListener {

	@Bind(R.id.commentContent)
	public EditText commentContent;
	@Bind(R.id.commentBtn)
	public TextView commentBtn;
	@Bind(R.id.toolbar)
	public Toolbar toolbar;
	@Bind(R.id.loadingView)
	public View loadingView;
	@Bind(R.id.detailContentLayout)
	public LinearLayout detailContentLayout;
	@Bind(R.id.comment_container)
	public LinearLayout commentContainer;
	@Bind(R.id.button_container)
	public LinearLayout actionButtonContainer;
	@Bind(R.id.comment)
	public TextView commentActionButton;
	@Bind(R.id.we_chat_dialog_container)
	public LinearLayout weChatContainer;

	protected BusinessModule bModule;
	protected String postId;
	protected T info;
	// 软件盘弹起后所占高度阀值
	private int keyHeight = 0;
	private boolean editTextShow = false;
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_discount_detail);
		dialog = new ProgressDialog(this, R.style.MyAlertDialogStyle);
		dialog.setTitle("");
		dialog.setMessage(getResources().getString(R.string.report_loading));
		dialog.setIndeterminate(false);
		dialog.setCancelable(true);

		bModule = imContext.getBusinessModule();

		Intent intent = getIntent();
		if (intent == null) {
			return;
		}

		String deepLink = intent.getDataString();
		if (intent.getDataString() != null) {
			postId = deepLink.substring(deepLink.lastIndexOf("/") + 1);
			if (StringUtil.isEmptyString(postId)) {
				return;
			}

			int indexOfChar = postId.indexOf("?");
			if (indexOfChar != -1) {
				postId = postId.substring(0, indexOfChar);
			}
		} else {
			postId = intent.getStringExtra("postId");
			if (StringUtil.isEmptyString(postId)) {
				return;
			}
		}

		toolbar.setTitle("");
		setSupportActionBar(toolbar);
		toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back));

		customizeLoadingView();
		loadingView.setVisibility(View.VISIBLE);
		detailContentLayout.setVisibility(View.GONE);
		updateInfo();
		if (info == null) {
			loadInfo(ATaskMark.TYPE_DEFAULT);
		} else {
			init();
		}

		// 获取屏幕高度
		int screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
		// 阀值设置为屏幕高度的1/3
		keyHeight = screenHeight / 3;
		// 添加layout大小发生改变监听器
		detailContentLayout.addOnLayoutChangeListener(this);

		detailContentLayout.setFocusable(true);
		detailContentLayout.setFocusableInTouchMode(true);
		detailContentLayout.requestFocus();

		if (hasActionButtons()) {
			actionButtonContainer.setVisibility(View.VISIBLE);
			commentContainer.setVisibility(View.INVISIBLE);
		} else {
			actionButtonContainer.setVisibility(View.GONE);
		}
	}

	protected void customizeLoadingView() {

	}

	@Override
	protected void onDestroy() {
		detailContentLayout.removeOnLayoutChangeListener(this);
		dialog.dismiss();
		super.onDestroy();
	}

	abstract protected void updateInfo();

	abstract protected void loadInfo(int type);

	abstract protected int commentCount();

	abstract protected void subInit();

	protected boolean hasActionButtons() {
		return false;
	}

	public T getInfo() {
		return info;
	}

	protected void init() {
		loadingView.setVisibility(View.GONE);
		detailContentLayout.setVisibility(View.VISIBLE);

		updateCommentBtn();
		subInit();
		detailContentLayout.requestFocus();

		Intent intent = getIntent();
		String showSoftInput = intent.getStringExtra("show_soft_input");
		String author = intent.getStringExtra("comment_author");
		String commentId = intent.getStringExtra("comment_id");
		// 从我的评论和@我的评论中点击回复跳转弹出软键盘
		if ("show_soft_input".equals(showSoftInput)) {
			HashMap<String, String> data = new HashMap<String, String>();
			data.put("parent_author", author);
			data.put("parent_id", commentId);
			Message msg = Message.obtain();
			msg.what = PhoConstants.ACTION_CITYNEWS_DETAIL;
			msg.obj = data;
			sendDelayMessage(msg,500);
		}

		String jumpType = intent.getStringExtra("from_my_comment");
		if ("from_my_comment".equals(jumpType)) {
			intent = new Intent(this, CityNewsCommentsActivity.class);
			intent.putExtra("postId", postId);
			startActivity(intent);
		}

		String postComment = intent.getStringExtra("post_comment");
		if("post_comment".equals(postComment)){
			Message msg = Message.obtain();
			msg.what = PhoConstants.ACTION_CITYNEWS_DETAIL;
			sendDelayMessage(msg,500);
		}
	}

	protected void updateCommentBtn() {
		if (editTextShow) {
			commentBtn.setText(R.string.right_btn);
			commentBtn.setTextColor(getResources().getColor(R.color.orange));
			return;
		}

		if (hasActionButtons()) {
			if (commentCount() > 0) {
				commentActionButton.setText(getString(R.string.comment_btn_str, commentCount()));
				commentActionButton.setTextColor(ContextCompat.getColor(this, R.color.orange));
			}

			commentActionButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(CommentDetailActivity.this, CityNewsCommentsActivity.class);
					intent.putExtra("postId", postId);
					startActivity(intent);
				}
			});
		} else {
			if (commentCount() == 0) {
				commentBtn.setTextColor(getResources().getColor(R.color.common_font));
				commentBtn.setText(getString(R.string.empty_comment));
			} else {
				commentBtn.setText(getString(R.string.comment_btn_str, commentCount()));
				commentBtn.setTextColor(getResources().getColor(R.color.orange));
			}
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@OnClick(R.id.commentBtn)
	public void onCommentBtnClick() {
		if (editTextShow) {
			postComment();
			return;
		}

		if (commentCount() == 0) {
			return;
		}

		Intent intent = new Intent(this, CityNewsCommentsActivity.class);
		intent.putExtra("postId", postId);
		startActivity(intent);
	}

	private void postComment() {
		String contentStr = commentContent.getText().toString().trim();
		if (StringUtil.isEmptyString(contentStr)) {
			return;
		}

		HashMap<String, String> data = (HashMap<String, String>) commentContent.getTag();
		String commentParentId = "";
		if (data != null && contentStr.contains("@" + data.get("parent_author"))) {
			commentParentId = data.get("parent_id");
		}
		userInsertComment(contentStr, commentParentId);
	}

	@SuppressLint("ResourceAsColor")
	private void userInsertParentComment(String author, String parentId) {
		commentContent.setText("@" + author + " " + commentContent.getText().toString() + " ");
		HashMap<String, String> data = new HashMap<String, String>();
		data.put("parent_author", author);
		data.put("parent_id", parentId);
		commentContent.setTag(data);
		commentContent.setSelection(commentContent.getText().toString().length());
		commentContent.setFocusable(true);
		commentContent.setFocusableInTouchMode(true);
		commentContent.requestFocus();
		InputMethodManager inputManager = (InputMethodManager) commentContent.getContext().getSystemService(
				Context.INPUT_METHOD_SERVICE);
		inputManager.showSoftInput(commentContent, 0);
	}

	private void userInsertComment(String contentStr, String commentParentId) {
		if (!AppUtils.getLoginStatus(this)) {
			return;
		}

		UserInfo userInfo = bModule.getCacheManager().getUserInfo();

		UserInsertCommentTaskMark aTaskMark = bModule.getTaskMarkPool().createUserInsertCommentTaskMark(postId,
				contentStr, commentParentId);
		bModule.getServiceWrapper().userInsertComment(this, aTaskMark, userInfo.getUserID(), postId, contentStr,
				commentParentId);
		InputMethodManager inputManager = (InputMethodManager) commentContent.getContext().getSystemService(
				Context.INPUT_METHOD_SERVICE);
		inputManager.hideSoftInputFromWindow(commentContent.getWindowToken(), 0);
		dialog.show();
	}

	public void userInsertParentComment(CommentInfo parentCommentInfo) {
		String comContent = commentContent.getText().toString().startsWith("@" + parentCommentInfo.getAuthor()) ? commentContent
				.getText().toString() : "@" + parentCommentInfo.getAuthor() + " " + commentContent.getText().toString();
		commentContent.setText(comContent);
		HashMap<String, String> data = new HashMap<String, String>();
		data.put("parent_author", parentCommentInfo.getAuthor());
		data.put("parent_id", parentCommentInfo.getId());
		commentContent.setTag(data);
		commentContent.setFocusable(true);
		commentContent.setFocusableInTouchMode(true);
		commentContent.requestFocus();
		Selection.setSelection(commentContent.getText(), commentContent.getText().length());
		InputMethodManager inputManager = (InputMethodManager) commentContent.getContext().getSystemService(
				Context.INPUT_METHOD_SERVICE);
		inputManager.showSoftInput(commentContent, 0);
	}

	public void updateMenu() {
		invalidateOptionsMenu();
	}

	@Override
	public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight,
			int oldBottom) {
		if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
			editTextShow = true;
			updateCommentBtn();

		} else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
			editTextShow = false;
			updateCommentBtn();
		}
	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		if (taskMark instanceof UserInsertCommentTaskMark) {
			if (taskMark.getTaskStatus() == ATaskMark.HANDLE_ERROR) {
				dialog.hide();
				Toast.makeText(this, R.string.report_error, 200).show();

			} else if (taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
				dialog.hide();
				commentContent.setText("");
			}
		}
	}

	@Override
	public void subHandleMessage(Message msg) {
		super.subHandleMessage(msg);

		switch(msg.what){
			case PhoConstants.ACTION_CITYNEWS_DETAIL:
				HashMap<String, String> data = (HashMap<String, String>) msg.obj;
				if(data!=null){
					String author = data.get("parent_author");
					commentContent.setText("@" + author + " " + commentContent.getText().toString() + " ");
					commentContent.setTag(data);
				}else{
					commentContent.setText("");
				}
				commentContent.setFocusable(true);
				commentContent.setFocusableInTouchMode(true);
				commentContent.requestFocus();
				Selection.setSelection(commentContent.getText(), commentContent.getText().length());
				InputMethodManager inputManager = (InputMethodManager) commentContent.getContext().getSystemService(
						Context.INPUT_METHOD_SERVICE);
				inputManager.showSoftInput(commentContent, 0);
				break;

			case Constants.BUSINESS_STATUS_INSERT_COMMENT:
				if(postId.equals(msg.obj)){
					loadInfo(ATaskMark.TYPE_REFRESH);
				}
				break;
		}
	}
}
